#include "FileSystemInfo.h"
#include "FileSystem.h"
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <iostream>

namespace FileSystem
{

FileSystemInfo::FileSystemInfo(const std::string &name, const bool isDir)
{
	this->fullName = name;
	uint ind = this->fullName.rfind(Separator) + 1;
	if (ind < 0)
		ind = 0;
	this->name = this->fullName.substr(ind, this->fullName.size() - ind);
	this->isDir = isDir;
}

FileSystemInfo::~FileSystemInfo()
{
}

void FileSystemInfo::MoveInto(const std::string &dirName)
{
	RenameTo(Combine(dirName, name));
}

void FileSystemInfo::RenameTo(const std::string &dest)
{
#ifdef WINDOWS

	string from = ("\"" + fullName + "\"");
	string to = ("\"" + dest + "\"");
	string cmd = string("copy /B /Y ") + from + " " + to;
	if (0 != system(cmd.c_str()))
	{
		cout << cmd.c_str() << "\n\tfailed\n";
		throw 122;
	}
	cmd = string("del /F /Q ") + from;
	if (0 != system(cmd.c_str()))
	{
		cout << cmd.c_str() << "\n\tfailed\n";
		throw 122;
	}


	//uint flag = 0;
	//do {
	//	if (rename(fullName.c_str(), dest.c_str()) < 0)
	//	{
	//		if (ENOENT == errno)
	//		{
	//			++flag;
	//			perror(fullName.c_str());
	//			break;
	//		}

	//		if ((flag < 2) && (remove(dest.c_str()) >= 0))
	//		{
	//			++flag;
	//			continue;
	//		}

	//		cout << "EXC_CANNOT_RENAME_FILE" << endl;
	//		perror(fullName.c_str());
	//		throw EXC_CANNOT_RENAME_FILE;
	//	}
	//}
	//while (false);

#else

	string from = ("\"" + fullName + "\"");
	string to = ("\"" + dest + "\"");
	string cmd = string("mv ") + from + " " + to;
	if (0 != system(cmd.c_str()))
	{
		cout << cmd.c_str() << "\n\tfailed\n";
		throw EXC_CANNOT_CREATE_DIR;
	}

#endif

}

DirInfo FileSystemInfo::GetParent() const
{
	uint index = fullName.rfind(Separator);
	string owner = "";
	if (index > 0) {
		owner = fullName.substr(0, index);
	}
	DirInfo di(owner);
	return di;
}

void FileSystemInfo::CopyTo(const std::string &dest)
{
	if (!GetParent().ExistsFile(name))
		return;	

#ifdef WINDOWS

	std::string from = ("\"" + fullName + "\"");
	std::string to = ("\"" + dest + "\"");
	std::string cmd = string("copy /Y /B ") + from + " /B " + to;
	if (0 != system(cmd.c_str()))
	{
		cout << cmd.c_str() << "\n\tfailed\n";
		throw 122;
	}

#else

	std::string from = ("\"" + fullName + "\"");
	std::string to = ("\"" + dest + "\"");
	std::string cmd = string("cp ") + from + " " + to;
	if (0 != system(cmd.c_str()))
	{
		cout << cmd.c_str() << "\n\tfailed\n";
		throw 122;
	}
	else
	{
		cout << "cmd: |" << cmd << "|\tsucced\n";
	}

#endif

}


std::string FileSystemInfo::GetName() const
{
	return name;
}

std::string FileSystemInfo::GetFullName() const
{
	return fullName;
}

bool FileSystemInfo::IsDir() const
{
	return isDir;
}

}
